# -- coding: utf-8 --
# @time :
# @author : 周梦泽
# @file : .py
# @software: pycharm

"""
gjc_hyc_main_run.py
关键词与行业词的主运行文件
"""
import glob
import os
import time
import traceback
from typing import List

import pandas as pd

from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc import gjc_data
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc_hyc_main.data_clean_main import gjc_hyc_data
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.parseExcelToTitle import ParseExcelToTitle
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.parseExcelToTitle.Title2Excel import title2excel
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.restockCycle.restock_cycle import order_date
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.throughTrain.promotion import AddCommodity
from autoTask.taobao.sycm.utils.csv_merge import read_csv
from common.logger.log import log_
from common.utils.CacheUtil import init_cache
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.keywordMergeCompeting.keyword_merge import merge_df
from common.utils.ExcelUtil import xw_copy_sheet_value, xw_get_has_content_row, xw_get_last_used_column, xw_del_sheet
import xlwings as xw


def run(params: dict, competing_path: List[str]):
    """
    开始执行总任务 获取数据 + 表格处理
    :param params: 包含下面两个任务的参数
        params1: rwss的任务与启动参数
        params2: gjc_data_clean 的任务参数
        params3: 表格处理的任务参数
    :param competing_path: 竞品表格路径
    :return:
    """

    log_.info('开始执行浏览器任务:\n\t任务参数：{}'.format(params))
    xgfx_result = init_cache(params).get_search_key_df(key_type='xgfx')
    ssph_result = init_cache(params).get_search_key_df(key_type='ssph')
    if xgfx_result is None or ssph_result is None:
        # 先看一下缓存有没有数据，没有就执行GetData
        get_data = gjc_data.GetData(params)
        get_data.start_run()

    log_.info('开始执行表格任务:\n\t任务参数：{}'.format(params))
    file_path = gjc_hyc_data(params)[0]
    competing_sheet_copy(file_path, competing_path)
    # time.sleep(5)
    merge_df(file_path)

    log_.info('开始生成补单周期表')
    day = params.get('dateCycle')
    order_date(excel_path=file_path, day=day)

    log_.info('开始生成标题表格')
    title2excel(excel_path=file_path, params=params)

    # 合并竞品词与关键词，并添加到excel中
    gjc_wb = xw.Book(file_path)
    xw_del_sheet(gjc_wb, '关键词+竞品词')
    gjc_wb.save()
    # 将表格中的关键词+竞品词sheet页删除
    try:
        # 是否需要自动修改标题
        if params.get("isOperationTitle"):
            ParseExcelToTitle(file_path)(params)
        if params.get("isAutoAppendKeyWord"):
            AddCommodity(params=params, excel_path=file_path).add_keywords()
    except Exception as e:
        log_.error(e)
        log_.error(traceback.format_exc())
        log_.error('程序执行失败，但依然还会返回表格')

    return file_path, 'xlsx'


def competing_sheet_copy(file_path, competing_path):
    """
    将竞品词表格复制到关键词表格中
    :param file_path:关键词表格路径
    :param competing_path:竞品词表格路径
    :return:
    """
    # 将竞品词添加到表格新的sheet中
    gjc_wb = xw.Book(file_path)
    competing_wb = xw.Book(competing_path[0])
    # 在该文件中新建一个工作表
    target_sheet = gjc_wb.sheets.add('竞品词')
    source_sheet = competing_wb.sheets[0]
    last_row = xw_get_has_content_row(source_sheet)
    # 获取行
    last_column = xw_get_last_used_column(source_sheet, last_row)
    # 获取列
    xw_copy_sheet_value(source_sheet, target_sheet, f'A1:{last_column}{last_row}', f'A1:{last_column}{last_row}')
    # 保存并关闭 Excel 文件
    gjc_wb.save()
    competing_wb.save()
    gjc_wb.close()
    competing_wb.close()


# def init_cache(params):
#     search_content = params['searchContent']
#     related_day = params['relatedDay']
#     hot_term_day = params['hotTermDay']
#     data_word = params['dataWord']
#     table_topic_list = params['tableTopic']
#
#     cache_table = CacheTable(search_content, data_word, related_day, hot_term_day, table_topic_list)
#     return cache_table


if __name__ == '__main__':
    data_params = {
        "account": "中山杰特电器:星星",
        "password": "yzt123456",
        "searchContent": "奶锅",
        "isOperationTitle": True,
        "isAutoAppendKeyWord": True,
        "relatedDay": 7,
        "hotTermDay": 30,
        "dataWord": "搜索词",
        "dealValue": 1000,
        "payNum": 30,
        "min_price": 128,
        "matchesType": "精准匹配",
        "blockWords": [
            "苏泊尔",
            "章丘",
            "官方",
            "空气炸锅",
            "炊大皇",
            "康巴赫",
            "铸铁锅",
            "树可",
            "卡罗特",
            "三禾",
            "wmf",
            "铁",
            "九阳",
            "陶",
            "双立",
            "帝",
            "荣",
            "爱",
            "乐"
        ],
        "dealNum": 10000,
        "hotIndex": 4,
        "searchNum": 10000,
        "payRate": 10.1,
        "numOfPay": 501,
        "targetProductMap": [
            {
                "productId": "671036943564",
                "titlePrefix": "赫巴兹361不锈钢",
                "titleSuffix": "煎炒煮一体",
                "titleMaxLength": 60,
                "ignoreCuts": [
                    "陶",
                    "角",
                    "电池",
                    "蒸",
                    "可用"
                ]
            }
        ]
    }
    # run(params=data_params)
